<template>
  <div id="contestsView">
    <div :style="{ display: 'flex' }">
      <a-card
        v-for="(card, index) in cardList"
        :key="index"
        :style="{ width: '400px', margin: '30px' }"
        :title="card.name"
        hoverable
        class="card-demo"
      >
        <div v-if="Date.parse(card.startTime) > now">
          <a-countdown
            title="距离比赛开始还有"
            :value="moment(card.startTime).format('YYYY/MM/DD HH:mm:ss')"
            :now="now"
            style="margin: 10px 0 10px 50px"
          />
        </div>
        <div
          v-else-if="
            Date.parse(card.startTime) + card.length * 60 * 1000 >= now
          "
        >
          <a-countdown
            @Click="toContestPage(card.id)"
            title="比赛已开始，点击进入"
            :value="now"
            :now="now"
            style="margin: 10px 0 10px 50px"
          />
        </div>
        <template #extra>
          <div v-if="!card.isSignUp">
            <div v-if="card.needPassword">
              <a-button type="text" @click="handleClick">报名</a-button>
              <a-modal
                v-model:visible="visible"
                @before-ok="handleBeforeOk(card.id)"
                :mask-style="{ backgroundColor: 'rgba(0, 0, 0, 0.1)' }"
                title="请输入密码"
                :closable="false"
              >
                <a-form>
                  <a-form-item field="password" label="密码">
                    <a-input v-model="password" />
                  </a-form-item>
                </a-form>
              </a-modal>
            </div>
            <a-button type="text" v-else @Click="signup(card.id)"
              >报名</a-button
            >
          </div>
          <div v-else>
            <div>
              <a-tag color="green">已报名</a-tag>
            </div>
          </div>
        </template>

        <a-card-meta
          :title="'比赛时间:' + card.startTime"
          :description="card.introduction"
        >
          <template #avatar>
            <div
              :style="{
                display: 'flex',
                alignItems: 'center',
                color: '#1D2129',
                margintop: '10px',
              }"
            >
              <a-typography-text
                >by: {{ card.writer.userName }}
              </a-typography-text>
            </div>
          </template>
        </a-card-meta>
      </a-card>
    </div>
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="name" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">提交</a-button>
      </a-form-item>
    </a-form>
    <a-divider size="0" />
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="{
        showTotal: true,
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
      }"
      @page-change="onPageChange"
    >
      <template #name="{ record }">
        <a-link @click="toContestPage(record.id)" status="warning"
          >{{ record.name }}
        </a-link>
      </template>
      <template #startTime="{ record }">
        {{ moment(record.startTime).format("YYYY/MM/DD") }}<br />
        {{ moment(record.startTime).format("HH:mm") }}
      </template>
      <template #length="{ record }">
        {{
          moment
            .utc(moment.duration(record.length, "minutes").asMilliseconds())
            .format("HH:mm")
        }}<br />
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  ContestControllerService,
  ContestQueryRequest,
  Page_Question_,
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import * as querystring from "querystring";
import { useRouter } from "vue-router";
import moment from "moment";
import { createApp } from "vue";
import ArcoVue, { Modal } from "@arco-design/web-vue";

const dateString = "2024-05-04 18:30:00";
const timestamp = Date.parse(dateString);
const now = Date.now();
const tableRef = ref();
const password = ref("");
const visible = ref(false);
const dataList = ref([]);
const cardList = ref([]);
const total = ref(0);
const searchParams = ref<ContestQueryRequest>({
  name: "",
  pageSize: 10,
  current: 1,
});

const handleClick = () => {
  visible.value = !visible.value;
};

const handleBeforeOk = async (contestId: number) => {
  await signup(contestId);
  return true;
};
const signup = async (contestId: number) => {
  const res = await ContestControllerService.signupContestUsingPost(
    contestId,
    password.value
  );
  password.value = "";
  if (res.code === 0) {
    message.success("报名成功");
    await loadData();
  } else {
    message.error("报名失败，" + res.message);
  }
};

const loadData = async () => {
  const res = await ContestControllerService.listContestVoByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records.filter(
      (contest) =>
        Date.parse(contest.startTime) + contest.length * 60 * 1000 < Date.now()
    );
    cardList.value = res.data.records.filter(
      (contest) =>
        Date.parse(contest.startTime) + contest.length * 60 * 1000 >= Date.now()
    );
    cardList.value.reverse();
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

// {id: "1", title: "A+ D", content: "新的题目内容", tags: "["二叉树"]", answer: "新的答案", submitNum: 0,…}

const columns = [
  {
    title: "历史比赛",
    slotName: "name",
  },
  {
    title: "作者",
    dataIndex: "writer.userName",
  },
  {
    title: "开始时间",
    slotName: "startTime",
  },
  {
    title: "比赛时间",
    slotName: "length",
  },
  {
    slotName: "acceptNum",
  },
];

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (id: number) => {
  router.push({
    path: `/view/question/${id}`,
  });
};

/**
 * 跳转到做题页面
 * @param question
 */
const toContestPage = (contestId: number) => {
  router.push({
    path: `/view/contest/${contestId}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>

<style scoped>
#contestsView {
  max-width: 1280px;
  margin: 0 auto;
}

.card-demo:hover {
  transform: translateY(-4px);
}
</style>
